﻿using System;
using System.Web.Helpers;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.UI
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class CustomValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        internal Action ValidateAction { get; private set; }

        public CustomValidateAntiForgeryTokenAttribute()
        {
            this.ValidateAction = new Action(AntiForgery.Validate);
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            try
            {
                this.ValidateAction();
            }
            catch (Exception ex)
            {
                filterContext.Result = new JsonResult
                {
                    ContentType = "application/json",
                    JsonRequestBehavior = 0,
                    Data = new { status = 0, msg = "不安全的操作，请刷新页面重新提交！" }
                };
            }
        }
    }
}